家庭任務平台是使用Laravel的Blade樣板語言。
前端使用者介面通常會有同一元件出現在不同地方的狀況,重複複製貼上是很沒有效率的事,因此要考慮如何元件複用,而blade就提供了Component可以重複利用元件。
假設現在任務(Tasks)也希望增加一個刪除的按鈕,而且希望元件跟計畫的刪除按鈕一樣,這時候就會需要能夠將固定值能夠轉成變數值。
<form class=" bg-blue-200" action="{{route('project.destory',['project'=>$project])}}" method="post">
@csrf
@method('DELETE')
<button class="button-add " type="submit">Delete</button>
</form>
希望變數能藉由賦值$deletedType, $deletedSubject來動態決定是任務或計畫。
<form class=" bg-blue-200" action="{{route($deletedType.'.destory',[$deletedType => $deletedSubject])}}" method="post">
@csrf
@method('DELETE')
<button class="button-add " type="submit">Delete</button>
</form>
藉由php artisan make:component DeleteButton做出按鈕元件,此時會新增兩個檔案個別在App\View\Components和resources/views/components資料夾中:
(1) App\View\Components : DeleteButton
(2) resources/views/components:delete-button.blade.php
因為希望能夠動態設定$deletedType,$deletedSubject的值,所以需要進行以下設定:
class DeleteButton extends Component
{
public $deletedType;
public $deletedSubject;
/**
* Create a new component instance.
*
* @return void
*/
public function __construct($deletedType,$deletedSubject)
{
$this->deletedType = $deletedType;
$this->deletedSubject = $deletedSubject;
}
/**
* Get the view / contents that represent the component.
*
* @return \Illuminate\View\View|string
*/
public function render()
{
return view('components.delete-button');
}
}
如果變數是原始值,如字串或整數等等,不需要在前面加上:,但如果變數是PHP表達式或是變數,則需要在前面加上:
<x-delete-button deletedType="project" :deletedSubject="$project" />
<x-delete-button deletedType="task" :deletedSubject="$task" />
參考文章: